import axios from 'axios';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import Seo from '@/core/components/Seo';
import dynamic from 'next/dynamic';
import { capitalizeEachWord } from '../../utils/capializeFIrstWord';

// ✅ Breadcrumb = default export
import Breadcrumb from '@/lib/category/components/Breadcrumb';

const BasicLayout = dynamic(
  () => import('@/core/components/layouts/BasicLayout'),
);
const ProductSearch = dynamic(
  () => import('@/lib/product/components/ProductSearch'),
);

export default function KeywordPage() {
  const route = useRouter();

  const [result, setResult] = useState(null);
  const [query, setQuery] = useState(null);
  const [categoryId, setCategoryId] = useState(null);

  const slugRaw = route.query.slug || null;
  const readableSlug = slugRaw
    ? decodeURIComponent(slugRaw)
        .replace(/-/g, ' ')
        .replace(/\b\w/g, (c) => c.toUpperCase())
    : '';

  // 🔹 Fetch searchkey dari Solr
  const getSearchKeyData = async (slug) => {
    try {
      const res = await axios(
        `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/searchkey?url=${slug}&from=searchkey`,
      );

      setResult(res?.data?.response?.docs?.[0] || null);
    } catch (e) {
      console.error('Fetching searchkey failed:', e);
    }
  };

  // 🔹 Trigger fetch saat slug siap
  useEffect(() => {
    if (!route.isReady || !slugRaw) return;
    getSearchKeyData(slugRaw);
  }, [route.isReady, slugRaw]);

  // 🔹 Ambil product_ids + categoryId dari Solr
  useEffect(() => {
    if (!result) return;

    // product search - keep ids for API, add from marker for ProductSearch
    const ids = result.product_ids_is || [];
    setQuery({
      ids: ids.join(','),
      from: 'searchkey',
    });

    // breadcrumb category
    const catId =
      result.category_id_i ||
      result.public_categ_id_i ||
      (result.category_ids_is && result.category_ids_is[0]);

    if (catId) {
      setCategoryId(catId);
    }
  }, [result]);

  return (
    <BasicLayout>
      <Seo
        title={`Beli ${readableSlug} Original & Harga Terjangkau - indoteknik.com`}
        description={`Beli ${readableSlug} Kirim Jakarta Surabaya Semarang Makassar Manado Denpasar.`}
        additionalMetaTags={[
          {
            property: 'keywords',
            content: `Beli ${readableSlug}, harga ${readableSlug}, ${readableSlug} murah`,
          },
        ]}
        canonical={`${process.env.NEXT_PUBLIC_SELF_HOST}${route.asPath}`}
      />

      {/* ✅ Breadcrumb (auto fetch via component) */}
      {categoryId && (
        <Breadcrumb categoryId={categoryId} currentLabel={readableSlug} />
      )}

      {/* ✅ Product result */}
      {query && (
        <ProductSearch query={query} prefixUrl={`/searchkey/${slugRaw}`} />
      )}
    </BasicLayout>
  );
}
